<?php

/**
 * 商城统计
 * TODO:重写逻辑，拆分，销售额的数字可能是好多9
 */

if (!class_exists('Npcink_B2_Shop')) {
    class Npcink_B2_Shop
    {


        public static function run($option)
        {
            //是否加载商城统计

            $b2_count = MaBox_Admin::get_config($option, 'b2_count');
            if ($b2_count) {
                require_once plugin_dir_path(__FILE__) . 'add_menu.php'; //载入文件
                Npcink_B2_Shop_Add_Menu::run_add_menu();
            }

            //是否添加订单菜单
            $add_order_menu = MaBox_Admin::get_config($option, 'add_order_menu');
            if ($add_order_menu) {
                add_action('admin_menu', array(__CLASS__, 'add_order_menu'));
            }
        }

        /**
         * 添加订单菜单
         */
        public static function add_order_menu()
        {
            add_menu_page(
                '订单处理',
                '订单处理入口',
                'administrator',
                'admin.php?page=b2_orders_list&order_state=f',
                '',
                "dashicons-list-view",
                1
            );
        }

        /**
         * 准备传递的数据
         */
        public static function deliver_data()
        {

            //准备对象
            $array = array(
                'shop' => array(
                    'today' => self::get_shop_today(), //今天销售数据
                    'month' => self::get_shop_month(), //本月销售数据
                    'form' => self::get_seven_data(), //最近7天销售数据
                ),

            );
            return $array;
        }

        /**
         * 拿到当天销售数据
         */
        public static function get_shop_today()
        {
            //今天的数据
            $option = self::handle_order_seven();
            $array = array(
                array(
                    'title' => "待发货",
                    'num' => (int)$option['shipped'],
                    'unit' => "个",
                    'icon' => "dashicons dashicons-store",
                ),
                array(
                    'title' => "总销售额",
                    'num' => (int)$option['today']['sale'],
                    'unit' => "￥",
                    'icon' => "dashicons dashicons-insert",
                ),
                array(
                    'title' => "总订单",
                    'num' => (int)$option['today']['sale_order'],
                    'unit' => "个",
                    'icon' => "dashicons dashicons-database-add",
                ),
                array(
                    'title' => "总退款",
                    'num' => (int)$option['today']['refund'],
                    'unit' => "￥",
                    'icon' => "dashicons dashicons-remove",
                ),
                array(
                    'title' => "总退款订单",
                    'num' => (int)$option['today']['refund_order'],
                    'unit' => "个",
                    'icon' => "dashicons dashicons-database-remove",
                ),

            );
            return $array;
        }
        /**
         * 月销售数据 - 整理数据
         */
        public static function get_shop_month()
        {
            //月数据
            $option = self::get_month_order();

            //准备对象
            $array = array(
                array(
                    'title' => "总销售额",
                    'num' => (int)$option['total_sales'],
                    'unit' => "￥",
                    'icon' => "dashicons dashicons-insert",
                ),
                array(
                    'title' => "总订单",
                    'num' => (int)$option['total_order'],
                    'unit' => "个",
                    'icon' => "dashicons dashicons-insert",
                ),
                array(
                    'title' => "总退款额",
                    'num' => (int)$option['total_refund_sales'],
                    'unit' => "￥",
                    'icon' => "dashicons dashicons-insert",
                ),
                array(
                    'title' => "总退款订单",
                    'num' => (int)$option['total_refund_order'],
                    'unit' => "个",
                    'icon' => "dashicons dashicons-insert",
                ),

            );
            return $array;
        }

        /**
         * 最近7天销售数据
         */
        public static function get_seven_data()
        {
            //最近7天数据
            $option = self::handle_order_seven();

            $array = array(
                array(
                    'title' => "总销售额(已减退款)",
                    'x' => $option['time'],
                    's' => array(
                        'title' => "总销售额",
                        'data' => $option['latelly']['sale'],
                    ),
                    'tooltip' => '元',
                ),
                array(
                    'title' => "总销售订单(已减退款订单)",
                    'x' => $option['time'],
                    's' => array(
                        'title' => "总订单",
                        'data' => $option['latelly']['sale_order'],
                    ),
                ),
                array(
                    'title' => "总退款额",
                    'x' => $option['time'],
                    's' => array(
                        'title' => "总退款额",
                        'data' => $option['latelly']['refund'],
                    ),
                    'tooltip' => '元',
                ),
                array(
                    'title' => "总退款订单",
                    'x' => $option['time'],
                    's' => array(
                        'title' => "总退款订单",
                        'data' => $option['latelly']['refund_order'],
                    ),
                ),
            );
            return $array;
        }



        /**
         * 拿到指定时间内的所有数据
         */
        public static function get_sql_data()
        {
            //用WordPress提供的全局变量
            global $wpdb;
            //实例化工具
            $tool = new MaBox_Tool;
            //拿到时间
            $time = $tool->get_time();
            $time = $time['a'];
            //拿到数据表
            $table_name = $wpdb->prefix . 'zrz_order';

            //创建数组，存储数据
            $array = array();

            //获取近7天的销售数据
            $order_data_seven = "SELECT order_type,order_commodity,order_state,order_date,order_total FROM $table_name WHERE  order_date > '$time[6]'";
            //原始数据
            $order_data = $wpdb->get_results($order_data_seven, ARRAY_A);

            //整理 - 将拿到的数据以时间为键名保存
            $array_data_time = array();
            //找到符合当前时间的值
            foreach ($order_data as $v) {
                //拿到当前键值的时间
                $value_time = $v['order_date'];
                //格式下一下
                $handle_value = date("Y-m-d", strtotime($value_time));
                $array_data_time[$handle_value][] = $v;
            }

            //$tool->p($array_data_time);

            //转成数组，每天的总销售额、总订单、总退款额、总退款订单

            /**
             * 筛选
             * 获取最近7天每天的销售数组
             */
            $order_seven_total = array();

            for ($i = 0; $i < count((array) $time); $i++) {
                //准备默认值
                $arr_default = array();

                //拿到时间格式化
                $t = date("Y-m-d", strtotime($time[$i]));

                //拿到当前时间的值，没有当前时间的，则为空值
                $value = isset($array_data_time[$t]) ? $array_data_time[$t] : $arr_default;
                //对数据进行筛查，保留所需数据

                $data = array_filter($value, function ($v) {
                    $switch = false;
                    //商城订单
                    if ($v['order_type'] == 'gx') {
                        //实物
                        if ($v['order_commodity'] == '1') {
                            //已发货
                            if ($v['order_state'] == 'q') {
                                $switch = true;
                            }
                            //已签收
                            if ($v['order_state'] == 'c') {
                                $switch = true;
                            }
                        }
                    }
                    return $switch;
                });

                //获取总销售额
                $total = 0;
                foreach ($data as $v) {

                    $total += $v['order_total'];
                }
                //时间
                $order_seven_total[$t]['time'] = $t;

                //总销售额，保留两位小数
                $order_seven_total[$t]['total'] = round($total, 2);

                //总销售订单 - 统计筛选后的数组有多少个
                $order_seven_total[$t]['order'] = count((array) $data);

                //拿到的数组键名会乱，这里重置下键名
                $order_seven_total[$t]['data'] = array_values($data);
            } //end for
            //$tool->p($order_seven_total);

            /**
             * 获取最近7天退款数组
             */
            $total_refund_data = array();
            for ($i = 0; $i < count((array) $time); $i++) {
                //准备默认值
                $arr_default = array();
                //拿到时间格式化
                $t = date("Y-m-d", strtotime($time[$i]));
                //先判断下，有时间则通过，没有时间则给默认值

                //拿到当前时间的值，没有当前时间的，则为空值
                $value = isset($array_data_time[$t]) ? $array_data_time[$t] : $arr_default;
                //对数据进行筛查，保留所需数据
                $data = array_filter($value, function ($v) {
                    $switch = false;
                    //商城订单
                    if ($v['order_type'] == 'gx') {
                        //实物
                        if ($v['order_commodity'] == '1') {
                            //已退款
                            if ($v['order_state'] == 't') {
                                $switch = true;
                            }
                        }
                    }
                    return $switch;
                });

                //获取退款总销售额
                $total = 0;
                foreach ($data as $v) {
                    $total += $v['order_total'];
                }

                $total_refund_data[$t]['time'] = $t;
                $total_refund_data[$t]['total'] = round($total, 2);
                $total_refund_data[$t]['order'] = count((array) $data);
                $total_refund_data[$t]['data'] = array_values($data);
            }
            //$tool->p($total_refund_data);
            /**
             * 待发货订单
             */
            $shipped_order = $wpdb->get_var("SELECT COUNT(*) FROM $table_name where order_state='f'");

            //创建数组，存储数据
            $array = array();
            //已售
            $array['sale'] = $order_seven_total;
            //已退
            $array['refund'] = $total_refund_data;
            //待发
            $array['shipped'] = $shipped_order;

            return $array;
        } //end get_sql_data()

        /**
         * 对拿到的数据进行二次处理
         */
        public static function handle_order_seven()
        {
            //实例化工具类
            $tool = new MaBox_Tool;
            //拿到数据
            $data = self::get_sql_data();
            //拿到时间
            $time = $tool->get_time();
            $time = $time['a'];

            //存储数据
            $arr = array();
            /**
             * 待发货订单
             */
            $arr['shipped'] = $data['shipped'];

            /**
             *今日统计
             */
            //今天的时间
            $today_time = date("Y-m-d", strtotime($time[0]));

            //今日总销售额
            $arr['today']['sale'] = $data['sale'][$today_time]['total'];

            //今日总订单
            $arr['today']['sale_order'] = $data['sale'][$today_time]['order'];

            //今日总退款
            $arr['today']['refund'] = $data['refund'][$today_time]['total'];

            //今日总退款订单
            $arr['today']['refund_order'] = $data['refund'][$today_time]['order'];

            /**
             * 表格用数据
             */
            //时间
            foreach ($time as $value) {
                $t[] = date("d", strtotime($value));
            }

            //最近7天总销售额
            $seven_sale_total = array();
            $seven_sale_total = array_column($data['sale'], 'total');
            //最近7天总订单
            $seven_sale_order = array();
            $seven_sale_order = array_column($data['sale'], 'order');

            //最近7天总退款
            $seven_refund_total = array();
            $seven_refund_total = array_column($data['refund'], 'total');

            //最近7天总退款订单
            $seven_refund_order = array();
            $seven_refund_order = array_column($data['refund'], 'order');

            //时间
            $arr['time'] = array_reverse($t);
            //数据
            $arr['latelly']['sale'] = array_reverse($seven_sale_total);
            $arr['latelly']['sale_order'] = array_reverse($seven_sale_order);
            $arr['latelly']['refund'] = array_reverse($seven_refund_total);
            $arr['latelly']['refund_order'] = array_reverse($seven_refund_order);
            //$tool->p($arr);
            return $arr;
        } //  handle_order_seven()

        /**
         * 月数据 - 拿到数据
         * 月总订单数（去退款）
         * 月总销售额（去退款）
         * 月总退款订单数
         * 月总退款额
         */
        public static function get_month_order()
        {

            //用WordPress提供的全局变量
            global $wpdb;
            //拿到表
            $table_name = $wpdb->prefix . 'zrz_order';

            //存储数据
            $arr = array();

            //数据库不存在
            if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
                //echo 'Table does not exist';
                $arr['total_sales'] = '0';
                $arr['total_order'] = '0';
                $arr['total_refund_sales'] = '0';
                $arr['total_refund_order'] = '0';
                return $arr;
            }

            //实例化工具
            $tool = new MaBox_Tool;
            //拿到时间
            $math = $tool->get_time_long('this_month');

            $start = '';
            $end = '';
            $start = $tool->export_handle_time('start', reset($math));
            $end = $tool->export_handle_time('end', end($math));

            //开始查询
            //总销售额
            $judge_later_a = "SELECT SUM(BINARY(order_total)) AS total FROM $table_name WHERE order_type = 'gx' and order_commodity = 1 and (order_state = 'c' or order_state = 'q') and order_date > '$start' and order_date < '$end'";
            //总订单数
            $judge_later_b = "SELECT COUNT(*) FROM $table_name WHERE order_type = 'gx' and order_commodity = 1 and (order_state = 'c' or order_state = 'q') and order_date > '$start' and order_date < '$end'";

            //总退款
            $judge_later_c = "SELECT SUM(BINARY(order_total)) AS refund FROM $table_name WHERE order_type = 'gx' and order_commodity = 1 and order_state = 't' and order_date > '$start' and order_date < '$end'";

            //总退款订单数
            $judge_later_d = "SELECT COUNT(*) FROM $table_name WHERE order_type = 'gx' and order_commodity = 1 and  order_state = 't' and order_date > '$start' and order_date < '$end'";
            //第二天到第7天拿到的值
            //总销售额
            $arr['total_sales'] = isset(($wpdb->get_results($judge_later_a, ARRAY_A))['0']['total']) ? ($wpdb->get_results($judge_later_a, ARRAY_A))['0']['total'] : 0;

            //总订单数
            $arr['total_order'] = $wpdb->get_var($judge_later_b);

            //总退款
            $arr['total_refund_sales'] = isset(($wpdb->get_results($judge_later_c, ARRAY_A))['0']['refund']) ? ($wpdb->get_results($judge_later_c, ARRAY_A))['0']['refund'] : 0;

            //总退款订单
            $arr['total_refund_order'] = $wpdb->get_var($judge_later_d);

            return $arr;
        }
    } //end class
}
